package com.gitee.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.bo.UserLoginBo;
import com.gitee.enums.ResponseEnum;
import com.gitee.exception.UserException;
import com.gitee.mapper.UserMapper;
import com.gitee.pojo.User;
import com.gitee.service.IUserService;
import com.gitee.utils.JwtUtil;
import com.gitee.vo.UserVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private WxMaService wxMaService;

    @Transactional
    @Override
    public String login(UserLoginBo userLoginBo) {
        // 获取微信用户session
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(userLoginBo.getCode());
        } catch (WxErrorException e) {
            throw new UserException(ResponseEnum.LOGIN_FAIL);
        }
        if (sessionInfo == null) {
            throw new UserException(ResponseEnum.LOGIN_FAIL);
        }
        // 解密用户信息
        WxMaUserInfo wxUserInfo = wxMaService.getUserService()
                .getUserInfo(sessionInfo.getSessionKey(),userLoginBo.getEncryptedData(), userLoginBo.getIv());
        if (wxUserInfo == null) {
            throw new UserException(ResponseEnum.LOGIN_FAIL);
        }
        String openId = wxUserInfo.getOpenId();
        //判断是否注册过，如果没注册过，则把用户信息写入数据库
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().eq(User::getOpenId, openId);
        User user = super.getOne(queryWrapper);
        if (user == null) {
            User newUser = new User();
            BeanUtils.copyProperties(wxUserInfo, newUser);
            newUser.setOpenId(openId);
            newUser.setEnabled(false);
            newUser.setAdmin(false);
            newUser.setGender(Boolean.valueOf(wxUserInfo.getGender()));
            super.save(newUser);
            user = newUser;
        }
        //创建JWT
        return JwtUtil.createJWT(user);
    }

    @Override
    public UserVo info(Integer userId) {
        User user = super.getById(userId);
        if (user == null) {
            throw new UserException(ResponseEnum.NO_USER);
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }
}
